import 'package:flutter/material.dart';

/// BasePage 是抽象的页面，所有页面都应该继承于它
/// [ResultType] 是页面 pop 时返回的数据类型。
abstract class BasePage<ResultType> extends StatefulWidget {
  /// 无需context跳转路由的关键，全局导航key
  static final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
  /// 需要子类实现的设置页面名称
  String get pageName;

  /// PageRoute 的 builder
  Widget _pageBuilder(BuildContext context) {
    return this;
  }

  /// 创建一个 PageRoute
  Route<ResultType> createPageRoute(WidgetBuilder builder, RouteSettings settings) {
    return MaterialPageRoute(
      settings: settings,
      builder: builder,
    );
  }

  /// 获取路由设置
  RouteSettings get settings => RouteSettings(name: pageName);

  /// 跳转路由
  Future<ResultType> active({bool replace}) {
    var page = createPageRoute(_pageBuilder, settings);
    assert(page.settings != null); // createPageRoute 函数必须设置 settings
    assert(page.settings.name != null); // settings 中必须包含name。
    if (replace == true) {
      return navigatorKey.currentState.pushReplacement(page);
    } else {
      return navigatorKey.currentState.push(page);
    }
  }
}
